package org.vnl.platform.impl.job.log;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.vnl.platform.job.IJob;
import org.vnl.platform.job.JobExecException;


/**
 * 利用Log4j的properties做Log4j的設定
 * 
 * @author Vaughan
 *
 */
public class Log4JPropertiesInitJob implements IJob {

    private static final Logger logger = Logger.getLogger(Log4JPropertiesInitJob.class);
    
    private static final String FILE_LOCATION = "FILE_LOCATION";
    
    private String fileLocation;
    
    @Override
    public void setParams(Map<String, ? extends Object> params) {
        Object obj = params.get(FILE_LOCATION);
        this.fileLocation = obj == null ? "log4j.properties" : obj.toString();
    }

    @Override
    public int exec() throws JobExecException {
        InputStream in = this.getClass().getResourceAsStream(fileLocation);
        if (in == null) 
            in = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileLocation);
        if (in == null) {
            try {
                in = new FileInputStream(fileLocation);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return RESULT_FAIL;
            }
        }
        try {
            Properties prop = new Properties();
            prop.load(in);
            PropertyConfigurator.configure(prop);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return RESULT_FAIL;
        } catch (IOException e) {
            e.printStackTrace();
            return RESULT_FAIL;
        }
        logger.debug("Debug On");
        logger.error("Error On");
        logger.fatal("Fatal On");
        logger.info("Info On");
        logger.trace("Trace On");
        logger.warn("Warn On");
        return RESULT_SUCCESS;
    }

    @Override
    public void reset() throws JobExecException {
        
    }

}
